const state = {
  cartItems: []
}

const mutations = {
  setCartItems(state, payload) {
    const { product, rootState } = payload
    const productFromCartItems = state.cartItems.find(p => p.id === product.id)

    if (productFromCartItems) {
      productFromCartItems.quantity++
    } else {
      state.cartItems.push({
        ...product,
        quantity: 1
      })
    }

    if (product.inventory > 0) {
      const result = rootState.products.all.find(p => p.id === product.id)
      result.inventory--
    }
  }
}

const actions = {
  addToCart({ commit, rootState }, product) {
    commit('setCartItems', {
      rootState, 
      product
    })
  }
}

const getters = {
  totalPrice(state) {
    return state.cartItems.reduce((sum, item) => {
      sum += item.price * item.quantity
      return sum
    }, 0)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions
}